import PowerNet from "./PowerNet";
import Q from "../lib/qunee-es";

import $ from "jquery";

// import "@fortawesome/fontawesome-free/css/all.min.css";
// import "mdbootstrap/js/bootstrap.min";
// import "mdbootstrap/js/popper.min";

import "mdbootstrap/css/bootstrap.min.css";
// import "mdbootstrap/css/style.css";
// import "mdbootstrap/css/mdb.css";
// import "mdbootstrap/js/jquery"
import "mdbootstrap/js/bootstrap";
// import "mdbootstrap/js/popper.min";
//fix bsCustomFileInput error , 不能注释掉
// import bsCustomFileInput from "mdbootstrap/js/modules/bs-custom-file-input";
// window.bsCustomFileInput = bsCustomFileInput;
// import "mdbootstrap/js/mdb";
// import "chart.js/dist/Chart";

import "../less/editor.less";
// import "../qunee/js";

import Toolbar from "./tools/Toolbar";
import PropBar from "./tools/PropBar";
import ProtoBar from "./tools/ProtoBar";

// let graph;
window.Q = Q;

//负责主画面各种操作
class PowerEditor extends PowerNet {
	constructor(options) {
		super(options);
	}

	initEditor() {
		this.initGraphEvents();
		this.toolBar = new Toolbar({ editor: this, selector: "#toolbar" });
		this.protoBar = new ProtoBar({ editor: this, selector: "#protobar" });
		this.propBar = new PropBar({ editor: this, selector: "#propbar" });
	}

	// 模板模式，子类必须实现的方法
	afterEditorRender() {}
	sendUpdateGraph(data) {}
	sendCreateElement(protoId, props, tempId) {}
	sendCreateElementByNode(node) {}
	sendDeleteElement(ids) {}
	sendUpdateElement(data) {}
	//容器事件设置
	initGraphEvents() {
		var self = this;
		var graph = this.graph;

		graph.onstart = function (evt) {
			console.log("onstart", evt.getData());
			self.propBar.show(evt.getData());
		};

		graph.enddrag = function (evt) {
			var ele = evt.getData();
			var sm = graph.selectionModel;
			for (var i = 0; i < sm.length; i++) {
				var ele = sm.get(i);
				if (ele) {
					if (ele instanceof Q.Node) {
						var x = parseInt(ele.x);
						var y = parseInt(ele.y);
						if (self.isMapGraph) {
							// 转变成经纬度
							var ll = self.graph.getLonLatFromPixel(x, y);
							x = ll.lat;
							y = ll.lng;
						}

						self.sendUpdateElement({
							Id: ele.id,
							Props: {
								x,
								y,
							},
						});
					}
				}
			}
		};

		graph.ondrop = function (evt) {
			console.log("graph.ondrop", evt);
			self.ondrop(evt);
		};
		var gm = graph.graphModel;

		// 元素属性变化触发
		gm.dataChangeDispatcher.addListener({
			onEvent: function (evt) {
				console.log("ele prop change", evt.kind);
				self.propBar.onElementChange(evt);
				if ("name" == evt.kind) {
					var ele = evt.source;
					var id = ele.id;
					if (id && self.isSender(ele) && self.hasNode(id)) {
						self.sendUpdateElement({ Id: ele.id, Sender: self.uuid, Props: { name: evt.value } });
						// self.send("element_update_props", { Id: ele.get("id"), Sender: self.uuid, Props: { name: evt.value } });
					}
				}
			},
		});

		//图元集合发生变化时（如添加，删除......）
		gm.listChangeDispatcher.addListener({
			// beforeEvent: function (evt) {
			// 	if ("add" == evt.kind) {
			// 		//添加元素
			// 		let node = evt.data;
			// 		let id = node.id;

			// 		// if (self.graph.getElement(id)) {
			// 		// 	return false;
			// 		// } else {
			// 		// 	self.sendCreateElementByNode(node);
			// 		// 	return true;
			// 		// }
			// 	}
			// 	return true;
			// },
			onEvent: function (evt) {
				Q.log("listChangeDispatcher " + evt.kind + " element");
				if ("add" == evt.kind) {
					let ele = evt.data;
					if (ele instanceof Q.Edge) {
						// let id = ele.id;
						let sender = ele.sender;
						if (sender && self.uuid != sender) {
							return;
						}
						if (!ele.tempId) {
							//request stage , rid:randomId
							ele.tempId = "" + Math.random();
							self.tempElements[ele.tempId] = ele;
							self.sendCreateElement(self.protoBar.currentProtoId * 1, { from: ele.from * 1, to: ele.to * 1 }, ele.tempId);
						}
					}
				}

				if ("remove" == evt.kind) {
					//删除元素
					var data = evt.data;
					var ids = [];
					if (Array.isArray(data)) {
						for (var i in evt.data) {
							var id = evt.data[i].id;
							if (!id || !(id in self.elements)) {
								//元素不存在，不需要重复删除
								return;
							}
							ids.push(id);
						}
					} else {
						var id = evt.data.id;
						if (!id || !(id in self.elements)) {
							//元素不存在，不需要重复删除
							return;
						}
						ids.push(id);
					}
					self.sendDeleteElement(ids);
				}
			},
		});
	}

	addDeleteButton(editor, graph) {
		var deleteButton = Q.createButton({
			name: "Delete",
			action: function () {
				graph.removeSelection();
			},
		});
		deleteButton.style.backgroundColor = "#2898E0";
		deleteButton.style.color = "#FFF";
		editor.toolbar.appendChild(deleteButton);
		deleteButton.style.display = "none";
		graph.selectionModel.listChangeDispatcher.addListener(function () {
			if (graph.selectionModel.length > 0) {
				deleteButton.style.display = "";
			} else {
				deleteButton.style.display = "none";
			}
		});
	}

	ondrop(evt) {
		evt.preventDefault();
		var data = evt.dataTransfer.getData("text");
		if (!data) {
			return;
		}
		try {
			var proto = JSON.parse(data);
			var p = this.graph.globalToLocal(evt);
			var l = this.graph.toLogical(p.x, p.y);
			var x = parseInt(l.x);
			var y = parseInt(l.y);
			var props =  { x, y }
			if (this.isMapGraph) {
				var ll = this.graph.getLonLatFromPixel(l.x, l.y);
				props.x = ll.lat;
				props.y = ll.lng;
				props.zoom = this.graph.map.getZoom()
			}
			this.sendCreateElement(proto.Id,props);
		} catch (e) {
			console.log(e);
		}
	}
}

export { PowerEditor };
